package com.cuotigou.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by g on 2017/8/5.
 */
public class CommonUtils {


    private static final Logger LOG = LoggerFactory.getLogger(CommonUtils.class);



    public static void main(String[] args) {
       String s = decToken("075ca14b0ae4cbac564dd99e879e8d4b5b01cb1a27bbb8fbMjQm5L+u5pS5");
        System.out.println(s);
//        System.out.println(createToken("1111","c7e4107839342bbae0e756b0ceb0a45f",12l,"王"));
    }

    //生成token
    public static String createToken(String mobile,String password,Long userId,String username){
        String md5 = getMD5(mobile).substring(8,24);
        String str =userId+"&"+username;
        String encode = encryptByBase64(str);
        return  md5+password+encode;
    }

    //解析token
    public static String decToken(String token) {
        String substring = token.substring(48);
        String message = decryptByBase64(substring);
        String[] dec = message.split("&");
        return dec[0].toString();
    }

    /**
     * base64加密
     * @param password
     * @return
     */
    public static String encryptByBase64(String password) {
        byte[] bytes = new byte[0];
        try {
            bytes = password.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new sun.misc.BASE64Encoder().encode(bytes);
    }

    /**
     * base64解密
     * @param encryptPwd
     * @return
     */
    public static String decryptByBase64(String encryptPwd) {
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b = new byte[0];
        try {
            b = decoder.decodeBuffer(encryptPwd);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(b, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    
    //MD5加密
    public static String getMD5(String str) {
        String re = null;
        byte encrypt[];
        try {
            byte[] tem = str.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("md5");
            md5.reset();
            md5.update(tem);
            encrypt = md5.digest();
            StringBuilder sb = new StringBuilder();
            for (byte t : encrypt) {
                String s = Integer.toHexString(t & 0xFF);
                if (s.length() == 1) {
                    s = "0" + s;
                }
                sb.append(s);
            }
            re = sb.toString();
            return re;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String genPayNo(String orderType) {//ST
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
        String rdm = RandomUtil.getRandom(6);
        String suf = orderType;
        return suf + sdf.format(new Date()) + rdm;
    }

    //xml转map
    public static Map<String, Object> getXmlElement_1(String xmlFile) {
        SAXReader saxReader = new SAXReader();
        Map<String, Object> map = new HashMap();
        try {
            Document document = DocumentHelper.parseText(xmlFile);
            Element users = document.getRootElement();
            for (Iterator i = users.elementIterator(); i.hasNext(); ) {
                Element user = (Element) i.next();
                map.put(user.getName(), user.getText().trim());
                for (Iterator j = user.elementIterator(); j.hasNext(); ) {
                    Element node = (Element) j.next();
                    for (Iterator k = node.elementIterator(); k.hasNext(); ) {
                        Element thre = (Element) k.next();
                        map.put(thre.getName(), thre.getText());
                    }
                    map.put(node.getName(), node.getText());
                }
            }
        } catch (DocumentException e) {
            System.out.println(e.getMessage());
        }
        return map;
    }

//  接收的报文转map
    public static Map<String, Object> getXmlElement(String xmlFile) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        Map<String, Object> map = new HashMap();
        Document document = DocumentHelper.parseText(xmlFile);
        Element users = document.getRootElement();
        Element rst = users.element("Rst");
        for (Iterator i = rst.elementIterator(); i.hasNext(); ) {
            Element thre = (Element) i.next();
            map.put(thre.getName(), thre.getTextTrim());
        }
        return map;
    }



    @SuppressWarnings("unchecked")
    public static Map<String, Object> Dom2Map(Document doc){
        Map<String, Object> map = new HashMap<String, Object>();
        if(doc == null)
            return map;
        Element root = doc.getRootElement();
        for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
            Element e = (Element) iterator.next();
            List list = e.elements();
            if(list.size() > 0){
                map.put(e.getName(), Dom2Map(e));
            }else
                map.put(e.getName(), e.getText());
        }
        return map;
    }
    @SuppressWarnings("unchecked")
    public static Map Dom2Map(Element e){
        Map map = new HashMap();
        List list = e.elements();
        if(list.size() > 0){
            for (int i = 0;i < list.size(); i++) {
                Element iter = (Element) list.get(i);
                List mapList = new ArrayList();

                if(iter.elements().size() > 0){
                    Map m = Dom2Map(iter);
                    if(map.get(iter.getName()) != null){
                        Object obj = map.get(iter.getName());
                        if(!obj.getClass().getName().equals("java.util.ArrayList")){
                            mapList = new ArrayList();
                            mapList.add(obj);
                            mapList.add(m);
                        }
                        if(obj.getClass().getName().equals("java.util.ArrayList")){
                            mapList = (List) obj;
                            mapList.add(m);
                        }
                        map.put(iter.getName(), mapList);
                    }else
                        map.put(iter.getName(), m);
                }
                else{
                    if(map.get(iter.getName()) != null){
                        Object obj = map.get(iter.getName());
                        if(!obj.getClass().getName().equals("java.util.ArrayList")){
                            mapList = new ArrayList();
                            mapList.add(obj);
                            mapList.add(iter.getText());
                        }
                        if(obj.getClass().getName().equals("java.util.ArrayList")){
                            mapList = (List) obj;
                            mapList.add(iter.getText());
                        }
                        map.put(iter.getName(), mapList);
                    }else
                        map.put(iter.getName(), iter.getText());
                }
            }
        }else
            map.put(e.getName(), e.getText());
        return map;
    }

  /*  //  接收的报文转List
    public static ArrayList<Map<String, Object>> getXmlElementList(String xmlFile) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        ArrayList<Map<String, Object>> lists = new ArrayList<>();
        Document document = DocumentHelper.parseText(xmlFile);
        int count = 1;
        Element root = document.getRootElement();
        // 查找指定节点名称QName的所有子节点elements
        List<Element> list = root.elements("RepayRslts");
        for (Element object : list) {

            HashMap<String, Object> map = new HashMap<>();
            for (Element element : (List<Element>) object.elements()) {
                map.put(element.getName(), element.getText());
            }
            lists.add(count, map);
            count++;
        }
        return lists;
    }
*/



    public static <T> T convertXmlStrToObject(Class<T> beanType, String xmlStr) {
        T xmlObject = null;
        try {
            JAXBContext context = JAXBContext.newInstance(beanType);
            // 进行将Xml转成对象的核心接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(xmlStr);
            xmlObject = (T) unmarshaller.unmarshal(sr);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return xmlObject;
    }



    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param mobile
     * @param content
     * @return
     */

    public static String sendPost(String mobile, String content) {
        String url = "http://client.movek.net:8888/sms.aspx";
        String param = "action=send&userid=1702&account=SDK-A1702-1702&password=526936&mobile=" + mobile + "&content=" + content + "&sendTime=&extno=";
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        LOG.info("短信回执信息==" + result);
        return result;
    }



    //隐藏手机中间4位数
    public static String concealMobile(String mobile){{
        StringBuilder sb = new StringBuilder();
        sb.append(mobile.substring(0,3));
        sb.append("****");
        sb.append(mobile.substring(7));
        return sb.toString();
    }}

    //获取订单号
    public static String getRechargeNo(String type){

        return type + System.nanoTime() + RandomUtil.getRandom(10).toString().substring(3);

    }

    /**
     * 微信支付获取随机串
     *
     * @param length
     * @return
     */
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";// 含有字符和数字的字符串
        Random random = new Random();// 随机类初始化
        StringBuffer sb = new StringBuffer();// StringBuffer类生成，为了拼接字符串

        for (int i = 0; i < length; ++i) {
            int number = random.nextInt(62);// [0,62)
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }


}
